package com.mgface.zookeeper.curator.function;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class 分布式Barrier {
	static DistributedBarrier db;
	public static void main(String[] args) throws Exception {
		String path = "/curator-barrier";
		ExecutorService exec = Executors.newFixedThreadPool(4);
		for (int i = 0; i < 4; i++) {
			exec.submit(()->{
				CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181")
				.retryPolicy(new ExponentialBackoffRetry(1_000, 3)).build();
				client.start();
				db = new DistributedBarrier(client, path);
				System.out.println("当前:"+Thread.currentThread().getName()+"号barrier设置,db:"+db);
				try {
					System.out.println(Thread.currentThread().getName()+"-1");
					db.setBarrier();//设置屏障节点(开始建立会话)
					System.out.println(Thread.currentThread().getName()+"-2");
					db.waitOnBarrier();//等待屏障释放
					System.out.println(Thread.currentThread().getName()+"-3");
					System.out.println("启动...");
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		exec.shutdown();
		TimeUnit.SECONDS.sleep(15);
		System.out.println("----------------------");
		db.removeBarrier();//释放屏障(移除节点)
	}

}
